import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JToggleButton;
import javax.swing.SwingUtilities;

import CLIPSJNI.FactAddressValue;
import CLIPSJNI.MultifieldValue;
import CLIPSJNI.PrimitiveValue;
import CLIPSJNI.SymbolValue;

public class Wspinaczka extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private CLIPSJNI.Environment clips;
	private Properties properties;
	private JPanel questionPanel;
	private JPanel radioPanel;
	private JPanel buttonPanel;
	private JLabel text;
	private JButton button;
	private ButtonGroup choiceButtnoGroup;
	private String assertedName;
	private String lastAssertedName = "";

	public Wspinaczka() {
		this.setTitle("System ekspercki wspomagajacy wybieranie drogi wspinaczkowej");
		this.setExtendedState(MAXIMIZED_BOTH);
		this.setVisible(true);
		this.setResizable(true);
		this.setLayout(new GridLayout(3, 1));

		
		questionPanel = new JPanel();
		radioPanel = new JPanel();
		radioPanel.setVisible(true);
		buttonPanel = new JPanel();

		this.add(questionPanel);
		this.add(radioPanel);
		this.add(buttonPanel);

		choiceButtnoGroup = new ButtonGroup();
		

		button = new JButton("TEXT");
		buttonPanel.add(button);

		text = new JLabel("Witamy w systemie eksperckim WSPINACZKA");
		questionPanel.add(text);

		clips = new CLIPSJNI.Environment();
		clips.load("control.clp");
		clips.load("wspin.clp");
		clips.reset();
		clips.run(1);

		properties = new Properties();
		loadProperties(new File("cfg.properties"));

		setButtonListener();
		nextQuestion();
	}

	public void nextQuestion() {
		radioPanel.removeAll();

		
		MultifieldValue currentStateMultifieldValue = (MultifieldValue) clips
				.eval("(find-all-facts ((?f currentState)) TRUE)");
		java.util.List<FactAddressValue> currentStateList = currentStateMultifieldValue
				.listValue();
		if (currentStateList.isEmpty()) {
			return;
		}
		FactAddressValue currentState = currentStateList.get(0);

		
		assertedName = currentState.getFactSlot("name").toString();
		if (assertedName.contentEquals(lastAssertedName)) {
			clips.run(1);
			nextQuestion();
			return;
		}
		lastAssertedName = assertedName;

		
		if (currentState.getFactSlot("state").toString().equals("final")) {
			button.setText(properties.getProperty("RESTART").toString());

			
			MultifieldValue namesMultifieldValue = (MultifieldValue) clips
					.eval("(find-all-facts ((?f result)) TRUE)");
			java.util.List<FactAddressValue> trackList = namesMultifieldValue
					.listValue();

			if (!trackList.isEmpty()) {
				ResultPanel resultPanel = new ResultPanel(trackList.size());
				resultPanel.getResultTable()
						.setPreferredScrollableViewportSize(
								new Dimension(radioPanel.getWidth(), radioPanel
										.getHeight()));
				radioPanel.add(resultPanel);
				text.setText(properties.getProperty("RESULTS_END_TEXT")
						.toString());
				for (FactAddressValue track : trackList) {
					resultPanel.getModel().addTrack(
							track.getFactSlot("name").getValue().toString(),
							track.getFactSlot("value").getValue().toString(),
							track.getFactSlot("secure").getValue().toString());
					/*
					 * System.out.println(track.getFactSlot("name").getValue()
					 * .toString());
					 * System.out.println(track.getFactSlot("value").getValue()
					 * .toString());
					 * System.out.println(track.getFactSlot("secure").getValue()
					 * .toString());
					 */
				}

			} else {
				text.setText(properties.getProperty("NO_RESULTS_END_TEXT")
						.toString());
			}

			this.repaint();
			return;
		} else if (currentState.getFactSlot("state").toString()
				.equals("initial")) {
			button.setText(properties.getProperty("START").toString());
		} else {
			button.setText(properties.getProperty("NEXT").toString());
		}

		
		String msg = ((SymbolValue) currentState.getFactSlot("text"))
				.stringValue();
		text.setText(properties.getProperty(msg).toString());

		

		radioPanel.removeAll();
		choiceButtnoGroup = new ButtonGroup();

		MultifieldValue answersMultifieldValue = (MultifieldValue) currentState
				.getFactSlot("answers");
		java.util.List<PrimitiveValue> answersList = answersMultifieldValue
				.listValue();

		for (PrimitiveValue answer : answersList) {
			JRadioButton rButton = new JRadioButton(properties.getProperty(
					answer.toString()).toString(), false);
			//System.out.println("radio" + answer);
			
			PrimitiveValue selected = currentState.getFactSlot("selected");

			if (answer.toString().equals(selected.toString())) {
				rButton.setSelected(true);
			}
			rButton.setVisible(true);
			rButton.setActionCommand(answer.toString());
			radioPanel.add(rButton);

			choiceButtnoGroup.add(rButton);
		}
		this.repaint();
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				new Wspinaczka();
			}
		});

	}

	public void setButtonListener() {
		button.addMouseListener(new MouseListener() {

			@Override
			public void mouseReleased(MouseEvent arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void mousePressed(MouseEvent arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void mouseExited(MouseEvent arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void mouseEntered(MouseEvent arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void mouseClicked(MouseEvent arg0) {

				if (button.getText().equals("Start")) {
					clips.assertString("(start)");
					//System.out.println("(start)");

					clips.run(1);
					nextQuestion();
					return;
				} else if (button.getText().equals("Dalej")) {
					for (Component component : radioPanel.getComponents()) {
						if (component instanceof JToggleButton) {
							JToggleButton button = (JToggleButton) component;
							if (button.isSelected()) {
								String toAssert = "(" + assertedName + " "
										+ button.getActionCommand() + ")";
								clips.assertString(toAssert);
								//System.out.println(toAssert);
							}
						}
					}

					clips.run(1);
					nextQuestion();
					return;
				} else if (button.getText().equals("Restart")) {
					clips.reset();
					//System.out.println("clips.reset");

					clips.run(1);
					nextQuestion();
					return;
				}

			}
		});
	}

	private void loadProperties(File file) {
		InputStream is;
		try {
			is = new FileInputStream(file);
			properties.load(is);
		} catch (FileNotFoundException e) {
			System.out.println("Cannot find configuration file.");
		} catch (IOException e) {
			System.out.println("Some problems with configuration file.");
		}
	}

}
